import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { getCartListApi, updateCartApi, delCartApi } from "@/api/cart";

export const useCartStore = defineStore("cart", () => {
  const cartList = ref([]);
  const getCartList = async () => {
    const {
      data: { list, cartTotal: total },
    } = await getCartListApi();
    cartList.value = list;
    cartList.value.forEach((item) => {
      item.checked = true;
    });
  };
  const totalPrice = computed(() => {
    return cartList.value.reduce((pre, item) => {
      if (item.checked) {
        return pre + item.goods.goods_price_min * item.goods_num;
      }
      return pre;
    }, 0);
  });
  const totalCount = computed(() => {
    return cartList.value.reduce((pre, item) => {
      if (item.checked) {
        return pre + item.goods_num;
      }
      return pre;
    }, 0);
  });
  const updateCart = async (goodsId, goodsNum, goodsSkuId) => {
    await updateCartApi(goodsId, goodsNum, goodsSkuId);
    cartList.value.find((item) => {
      if (item.goods_id === goodsId) {
        item.goods_num = goodsNum;
      }
    });
  };
  const isAllChecked = computed({
    get() {
      return cartList.value.every((item) => item.checked);
    },
    set(newValue) {
      cartList.value.forEach((item) => (item.checked = newValue));
    },
  });
  const selectedOrder = computed(() => {
    return cartList.value.filter((item) => item.checked);
  });
  const selectedOrderIds = computed(() => {
    return selectedOrder.value.map((item) => item.id);
  });
  const delCart = (id) => {
    delCartApi([id]);
    cartList.value = cartList.value.filter((item) => item.id !== id);
  };
  const clearCart = () => {
    cartList.value = [];
  };

  return {
    cartList,
    getCartList,
    totalPrice,
    totalCount,
    isAllChecked,
    updateCart,
    delCart,
    selectedOrder,
    clearCart,
    selectedOrderIds,
  };
});
